

const chatUrl = "http://localhost:3000/chat";
let eventSource;
$(document).ready(function () {
  var messages = [];

  $("#prompt").on("keyup", function (event) {
    if (event.keyCode === 13) {
      sendMessage();
    }
  });

  $(".send").on("click", function () {
    sendMessage();
  });

  const sendMessage = () => {
    var promptValue = $("#prompt").val().trim();
    if (promptValue !== "") {
      messages.push({ role: "user", content: promptValue });
      var latestEntries = messages.slice(-5);
      listenToMessages(latestEntries);
      $("#prompt").val("");
    }
  }

  let eventSource;

  const listenToMessages = (messages) => {
    // 关闭旧的连接
    if (eventSource) {
      eventSource.close();
    }

    const ctrl = new AbortController();
    fetchEventSource(chatUrl, {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
      },
      body: JSON.stringify({ messages: messages }),
      signal: ctrl.signal,
      onmessage(event) {
        console.log(event);
        handleSSEData(event.id, event.data);
      },
      onerror(error) {
        console.error("EventSource failed with error:", error);
        eventSource?.close();
      },
      onclose: () => {
        console.log("连接关闭");
      },
    });
  };


  const handleSSEData = (id, data) => {

    var eventData = data
    var text = eventData.output.text;

    if (id === "1") {
      messages.push({ role: "assistant", content: text });
    } else {
      messages[messages.length - 1] = { role: "assistant", content: text };
    }

    renderMessages();
  }

  const renderMessages = () => {
    $("#chatBox").empty();
    messages.forEach(function (message) {
      var roleClass = message.role === "user" ? "user" : "assistant";
      var content = message.content;
      var renderedContent = marked.parse(content);
      $("#chatBox").append(
        '<div class="chat-content"><div class="role"><img src="' +
        (roleClass === "user"
          ? "./img/role/user.svg"
          : "./img/role/assistant.svg") +
        '" alt=""></div><div class="' +
        roleClass +
        '">' +
        renderedContent +
        "</div></div>"
      );
    });
    scrollToBottom();
  }


  const scrollToBottom = () => {
    $("#chatBox").scrollTop($("#chatBox")[0].scrollHeight);
  }
});
